function [x,objval,LPslack] = solve_samp(N_prefs, N_alphas, alpha_list, start_H)
% Solves QP to determine whether payoff parameters yield equilibrium.

global N N_types obs_shares
global C_sparse hyp_lim
global muZpH_vec
global LPopts



%% CONSTRAINTS

tic

% A) Lower Bounds = Zero

lb = zeros(N_alphas + 2*N_types,1);

% B) Alphas Add to 1

% Storage:

a = ones(N_prefs,1);
A = sparse([],[], true, N_prefs,N_alphas, N_alphas);

% Populate rows for each preference class:

for H = 1:(length(start_H)-1)
    first = start_H(H);
    last = start_H(H+1)-1;
    %
    A(H,first:last) = true;
end

% Last preference class:

H = N_prefs;
first = start_H(H);
last = N_alphas;
A(H,first:last) = true;

% C) Match Type Shares

% Matrix to get type measures from vector of allocation parameters:

muZpH_mat = sparse(double(alpha_list),1:N_alphas, muZpH_vec, N_types,N_alphas);

% D) Combine Equality Constraints

a_eq = vertcat(a, obs_shares);
A_eq = vertcat( [A sparse(N_prefs,2*N_types)], ...
                [muZpH_mat, speye(N_types), -speye(N_types)]  );

% E) Inequality Constraints for Confidence Region

% Max half-width of hyper-cube:

a_in = hyp_lim * ones(2*N_types, 1);

% Matrix with Cholesky decomp. of inverse variance:

A_in = vertcat( [sparse(N_types, N_alphas)  C_sparse -C_sparse], ...
                [sparse(N_types, N_alphas) -C_sparse  C_sparse] );

disp('Make constraints:')
toc



%% LP TO MATCH TYPE SHARES

% Objective - sum of slacks:

addslacks = sparse(N_alphas + (1:2*N_types),1,1);

% Solve LP:

tic
disp('LP problem:')
[startpt,LPslack,LPexitflag] = linprog(addslacks,A_in,a_in,A_eq,a_eq,lb,[],[],LPopts);
toc

% Sum of slacks (sum abs. deviations):

LPslack

% Set objval if cannot fit of observed shares:

if LPexitflag < 1
    x = [];
    objval = 1
end



%% QP FOR EQUILIBRIUM

% Only solve QP if prediction falls in confidence region:

if LPexitflag == 1

% Call KNITRO:

[x,objval,QPexitflag] = knitromatlab(@QP_obj, startpt, A_in,a_in, A_eq,a_eq, lb,[], [],[],[], 'knitro.opt');

% Values if QP fails to find feasible solution:
% (cannot predict type shares within confidence region)

if QPexitflag == -204 || QPexitflag == -205
    x = [];
    objval = 1
end

end  %  IF LPexitflag == 1



end
